<template>
  <div class="app-container">
    <!-- 标题区域 -->
    <div class="header">
      <div class="header-left">
        <h1>用户画像分析仪表盘</h1>
        <p>基于用户行为画像数据的多维度分析：演员偏好、价值分层、行为特征、观看习惯等</p>
      </div>
      <div class="header-right">
        <el-button
          type="warning"
          size="small"
          icon="el-icon-refresh"
          @click="refreshData"
          :loading="loading"
        >
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <!-- 第一行：演员偏好和RFM分层 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="chart-container">
              <div class="chart-title">演员偏好TOP15</div>
              <div id="actorPreferenceChart" class="chart" style="height: 400px;"></div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="chart-container">
              <div class="chart-title">RFM用户价值分层</div>
              <div id="rfmAnalysisChart" class="chart" style="height: 400px;"></div>
            </div>
          </el-col>
        </el-row>

        <!-- 第二行：时间趋势图 -->
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="24">
            <div class="chart-container">
              <div class="chart-title">用户分层随时间变化趋势</div>
              <div id="timeTrendChart" class="chart" style="height: 400px;"></div>
            </div>
          </el-col>
        </el-row>

        <!-- 第三行：雷达图和观看时长 -->
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <div class="chart-container">
              <div class="chart-title">分层用户行为特征雷达图</div>
              <div id="behaviorRadarChart" class="chart" style="height: 350px;"></div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="chart-container">
              <div class="chart-title">观看时长分布</div>
              <div id="watchDurationChart" class="chart" style="height: 350px;"></div>
            </div>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getDashboardData } from '@/api/analysis/user-analysis'

export default {
  name: 'UserAnalysis',
  data() {
    return {
      charts: {},
      dashboardData: {},
      loading: false
    }
  },
  mounted() {
    this.initCharts()
    this.loadData()
  },
  beforeDestroy() {
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose()
      }
    })
  },
  methods: {
    initCharts() {
      this.charts.actorPreference = echarts.init(document.getElementById('actorPreferenceChart'))
      this.charts.rfmAnalysis = echarts.init(document.getElementById('rfmAnalysisChart'))
      this.charts.behaviorRadar = echarts.init(document.getElementById('behaviorRadarChart'))
      this.charts.timeTrend = echarts.init(document.getElementById('timeTrendChart'))
      this.charts.watchDuration = echarts.init(document.getElementById('watchDurationChart'))

      window.addEventListener('resize', this.handleResize)
    },

    async loadData() {
      this.loading = true
      try {
        const response = await getDashboardData()
        this.dashboardData = response.data
        console.log('完整数据响应:', this.dashboardData)

        await this.loadNewChartData()
        this.renderCharts()
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('数据加载失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },

    async callUserProfileAPI(endpoint) {
      try {
        const response = await fetch(`http://localhost:8080/system/userProfile/${endpoint}`)
        const result = await response.json()
        console.log(`API ${endpoint} 返回:`, result)
        return result.code === 200 ? result.data : []
      } catch (error) {
        console.error(`调用 ${endpoint} 失败:`, error)
        return []
      }
    },

    async loadNewChartData() {
      try {
        console.log('开始加载新图表数据...')

        const [actorData, rfmData] = await Promise.all([
          this.callUserProfileAPI('actorPreferences'),
          this.callUserProfileAPI('rfmAnalysis')
        ])

        this.dashboardData.actorPreferences = actorData
        this.dashboardData.rfmAnalysis = rfmData

        console.log('演员偏好数据:', this.dashboardData.actorPreferences)
        console.log('RFM分析数据:', this.dashboardData.rfmAnalysis)

      } catch (error) {
        console.error('加载新图表数据失败:', error)
        this.dashboardData.actorPreferences = []
        this.dashboardData.rfmAnalysis = []
      }
    },

    renderCharts() {
      this.renderActorPreferenceChart()
      this.renderRFMAnalysisChart()
      this.renderBehaviorRadarChart()
      this.renderTimeTrendChart()
      this.renderWatchDurationChart()
    },

    renderActorPreferenceChart() {
      const data = this.dashboardData.actorPreferences || []
      console.log('原始演员偏好数据:', data)

      const filteredData = data.filter(item => {
        return item &&
          item.name !== null &&
          item.name !== undefined &&
          String(item.name).trim() !== '' &&
          String(item.name).toLowerCase() !== 'nan'
      })

      console.log('过滤后的演员偏好数据:', filteredData)

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          backgroundColor: 'rgba(255,255,255,0.95)',
          borderColor: '#e6a23c',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          axisLabel: {
            color: '#666',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: '#e6a23c'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#fdf6ec',
              type: 'dashed'
            }
          }
        },
        yAxis: {
          type: 'category',
          data: filteredData.map(item => item.name),
          axisLabel: {
            color: '#666',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: '#e6a23c'
            }
          }
        },
        series: [{
          name: '偏好度',
          type: 'bar',
          data: filteredData.map(item => item.value),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#f6d365' },
              { offset: 0.7, color: '#fda085' },
              { offset: 1, color: '#e6a23c' }
            ]),
            borderRadius: [0, 4, 4, 0]
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(230, 162, 60, 0.5)'
            }
          },
          label: {
            show: true,
            position: 'right',
            color: '#e6a23c',
            fontWeight: 'bold'
          }
        }]
      }
      this.charts.actorPreference.setOption(option)
    },

    // 修改后的RFM用户价值分层图（去掉流失风险用户）
    renderRFMAnalysisChart() {
      let data = this.dashboardData.rfmAnalysis || []
      console.log('RFM分析原始数据:', data)

      // 过滤掉流失风险用户
      data = data.filter(item => item.name !== '流失风险用户')
      console.log('过滤后的RFM数据:', data)

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
          backgroundColor: 'rgba(255,255,255,0.95)',
          borderColor: '#e6a23c',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          }
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'center',
          textStyle: {
            color: '#666',
            fontSize: 12
          }
        },
        color: ['#f6d365', '#fda085', '#e6a23c', '#ff9a9e'],
        series: [{
          name: '用户价值分层',
          type: 'pie',
          radius: ['45%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 3,
            shadowBlur: 10,
            shadowColor: 'rgba(230, 162, 60, 0.2)'
          },
          label: {
            show: false,
            position: 'center',
            formatter: '{b}\n{c} ({d}%)',
            fontSize: 14,
            fontWeight: 'bold'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            },
            scale: true,
            scaleSize: 5
          },
          labelLine: {
            show: false
          },
          data: data.map(item => ({
            name: item.name,
            value: item.value
          }))
        }]
      }

      this.charts.rfmAnalysis.setOption(option)
    },

    // 修改后的时间趋势图（去掉流失用户和忠实粉丝）
    renderTimeTrendChart() {
      const data = this.dashboardData.timeTrend || []
      console.log('时间趋势数据:', data)

      const timePoints = [...new Set(data.map(item => item.date))].sort()

      // 只保留重度用户、中度用户、轻度用户
      const tiers = ['重度用户', '中度用户', '轻度用户']

      const colors = ['#e74c3c', '#3498db', '#2ecc71', '#f39c12', '#9b59b6', '#1abc9c']

      const seriesData = tiers.map((tier, index) => {
        const values = timePoints.map(date => {
          const item = data.find(d => d.date === date && d.tier === tier)
          return item ? (item.count || 0) : 0
        })
        return {
          name: tier,
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            width: 3,
            shadowColor: colors[index],
            shadowBlur: 8,
            shadowOffsetY: 4
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: colors[index] + '80' },
              { offset: 1, color: colors[index] + '10' }
            ])
          },
          itemStyle: {
            color: colors[index],
            borderColor: '#fff',
            borderWidth: 2
          },
          emphasis: {
            focus: 'series',
            itemStyle: {
              borderColor: colors[index],
              borderWidth: 3,
              shadowBlur: 10,
              shadowColor: colors[index] + '80'
            }
          },
          data: values
        }
      })

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#e6a23c'
            }
          },
          backgroundColor: 'rgba(255,255,255,0.95)',
          borderColor: '#e6a23c',
          borderWidth: 1
        },
        legend: {
          data: tiers,
          top: '5%',
          textStyle: {
            color: '#666'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: timePoints,
          axisLine: {
            lineStyle: {
              color: '#e6a23c'
            }
          },
          axisLabel: {
            color: '#666'
          }
        },
        yAxis: {
          type: 'value',
          min: 0,
          axisLine: {
            lineStyle: {
              color: '#e6a23c'
            }
          },
          axisLabel: {
            color: '#666'
          },
          splitLine: {
            lineStyle: {
              color: '#fdf6ec',
              type: 'dashed'
            }
          }
        },
        series: seriesData
      }
      this.charts.timeTrend.setOption(option)
    },

    renderBehaviorRadarChart() {
      const data = this.dashboardData.behaviorRadar || []
      console.log('雷达图原始数据:', data)

      if (data.length === 0) {
        const option = {
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'center',
            textStyle: {
              color: '#999',
              fontSize: 16
            }
          }
        }
        this.charts.behaviorRadar.setOption(option)
        return
      }

      const option = {
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(255,255,255,0.95)',
          borderColor: '#e6a23c',
          borderWidth: 1
        },
        legend: {
          data: data.map(item => item.tier),
          bottom: 10,
          textStyle: {
            color: '#666'
          }
        },
        radar: {
          shape: 'circle',
          radius: '65%',
          splitNumber: 4,
          axisName: {
            color: '#666',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(253, 246, 236, 0.8)'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(253, 246, 236, 0.8)'
            }
          },
          splitArea: {
            show: true,
            areaStyle: {
              color: ['rgba(253, 246, 236, 0.2)', 'rgba(253, 246, 236, 0.4)']
            }
          },
          indicator: [
            { name: '平均观看时长', max: 100 },
            { name: '完播率', max: 100 },
            { name: '点赞率', max: 100 },
            { name: '评论率', max: 100 },
            { name: '收藏率', max: 100 },
            { name: '平均评分', max: 5 }
          ]
        },
        series: [{
          type: 'radar',
          emphasis: {
            lineStyle: {
              width: 4
            }
          },
          data: data.map(item => ({
            value: [
              item.avgWatchDuration || 0,
              item.completionRate || 0,
              item.likeRate || 0,
              item.commentRate || 0,
              item.collectRate || 0,
              item.avgRating || 0
            ],
            name: item.tier,
            symbolSize: 6,
            lineStyle: {
              width: 2
            },
            areaStyle: {
              opacity: 0.3
            }
          }))
        }]
      }
      this.charts.behaviorRadar.setOption(option)
    },

    renderWatchDurationChart() {
      const data = this.dashboardData.watchDuration || []
      console.log('观看时长数据:', data)

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          backgroundColor: 'rgba(255,255,255,0.95)',
          borderColor: '#e6a23c',
          borderWidth: 1
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.durationRange),
          name: '观看时长',
          axisLine: {
            lineStyle: {
              color: '#e6a23c'
            }
          },
          axisLabel: {
            color: '#666',
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '用户数量',
          axisLine: {
            lineStyle: {
              color: '#e6a23c'
            }
          },
          axisLabel: {
            color: '#666'
          },
          splitLine: {
            lineStyle: {
              color: '#fdf6ec',
              type: 'dashed'
            }
          }
        },
        series: [{
          data: data.map(item => item.userCount || 0),
          type: 'bar',
          itemStyle: {
            color: function(params) {
              const colors = [
                new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#e74c3c' },
                  { offset: 1, color: '#c0392b' }
                ]),
                new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#3498db' },
                  { offset: 1, color: '#2980b9' }
                ]),
                new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2ecc71' },
                  { offset: 1, color: '#27ae60' }
                ]),
                new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#f39c12' },
                  { offset: 1, color: '#e67e22' }
                ]),
                new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#9b59b6' },
                  { offset: 1, color: '#8e44ad' }
                ]),
                new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#1abc9c' },
                  { offset: 1, color: '#16a085' }
                ])
              ];
              return colors[params.dataIndex % colors.length];
            },
            borderRadius: [4, 4, 0, 0],
            shadowColor: 'rgba(0, 0, 0, 0.2)',
            shadowBlur: 6,
            shadowOffsetY: 3
          },
          emphasis: {
            itemStyle: {
              shadowColor: 'rgba(230, 162, 60, 0.5)',
              shadowBlur: 10
            }
          },
          label: {
            show: true,
            position: 'top',
            color: '#e6a23c',
            fontWeight: 'bold'
          }
        }]
      }
      this.charts.watchDuration.setOption(option)
    },

    refreshData() {
      this.loadData()
      this.$message.success('数据刷新成功')
    },

    handleResize() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.resize()
        }
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background: linear-gradient(135deg, #fef5e7 0%, #fdf6ec 100%);
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(90deg, #f6d365 0%, #ffffff 100%);
  padding: 30px;
  border-radius: 10px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.header-left {
  flex: 1;
}

.header-left h1 {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 10px 0;
}

.header-left p {
  font-size: 16px;
  color: #303133;
  opacity: 0.9;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-right button {
  background-color: #fda085;
  border-color: #fda085;
  color: #303133;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.header-right button:hover {
  background-color: #e6a23c;
  border-color: #e6a23c;
  transform: translateY(-2px);
}

.chart-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  height: 100%;
  border: 1px solid #fdf6ec;
  box-shadow: 0 2px 8px rgba(230, 162, 60, 0.05);
  transition: all 0.3s ease;
}

.chart-container:hover {
  box-shadow: 0 4px 16px rgba(230, 162, 60, 0.1);
  transform: translateY(-2px);
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #7c5a1c;
  text-align: center;
  padding-bottom: 12px;
  border-bottom: 2px solid #fdf6ec;
  position: relative;
}

.chart-title::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 2px;
  background: linear-gradient(135deg, #f6d365 0%, #e6a23c 100%);
  border-radius: 1px;
}

.chart {
  width: 100%;
}
</style>
